package com.mercycrazy.recruit.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

/**
 * Default Json Serializer Config (Jackson)
 *
 * @author <a href="mailto:1443424326@qq.com">mercycrazy</a>
 * @since 2023-01-10
 */
@Configuration
public class JsonSerializerConfig {

    private final Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;

    public JsonSerializerConfig(Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
        this.jackson2ObjectMapperBuilder = jackson2ObjectMapperBuilder;
    }

    @Bean
    public ObjectMapper jacksonObjectMapper() {

        ObjectMapper objectMapper = jackson2ObjectMapperBuilder
                .createXmlMapper(false).build();

        // 忽略 value 为 null 时 key 的输出
//        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 长整型和浮点型在 JavaScript 上面都会丢失精度, 所以要转换成字符串类型
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        module.addSerializer(Double.class, ToStringSerializer.instance);
        module.addSerializer(Double.TYPE, ToStringSerializer.instance);
        module.addSerializer(Float.class, ToStringSerializer.instance);
        module.addSerializer(Float.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(module);

        return objectMapper;
    }
}
